/**
 * 表单通用
 * author xty
 */
//通用初始化校验环境
$.validator.setDefaults({
    submitHandler: function() {}});
//注册表单校验事件
function regValidate(forms) {
    if(forms&&forms.length&&forms.length>0){
        for(var i in forms){
            $(forms[i]).validate({
                errorPlacement:function(error,element) {
                    // error.appendTo(element.parents('div .form-group'));
                    var findEle = element.next('.tip');
                    if(!findEle || findEle.length < 1){
                        findEle = element.parents().next('.tip');
                    }
                    error.appendTo(findEle);
                },
                // 聚焦事件
                // onfocusin: function(element) { $(element).valid(); },
                // 失焦事件
                onfocusout: function(element) { $(element).valid(); },
                // 点击事件
                onclick: function(element) { $(element).valid(); },
                // 键盘事件
                onkeyup: function(element) { $(element).valid(); }
            });
        }
    }
}

//获取表单数据
function getFormData(form) {
    var params = $(form).serializeArray();
    var values = {};
    for( x in params ){
        if(params[x].name in values){
            if(Array.isArray(values[params[x].name])){
                values[params[x].name].push(params[x].value);
            }else{
                values[params[x].name]=[values[params[x].name],params[x].value];
            }
        }else{
            values[params[x].name] = params[x].value;
        }
    }
    return values
}

//  弹框的页面提示取消
function resetFormTip(form) {
    var validateobj = $(form).validate({
        onfocusout: function(element) { $(element).valid();
        }
    });
    validateobj.resetForm();
}

function resetInputCss(form) {
    var path = form + ' div div input';
    $(path).attr('class', 'form-control');
}
//初始化下拉框信息
function initSelectList(obj,data,key,value){
    if(!key) key='id';
    if(!value) value='name';
    $(obj).empty();
    var htmStr=" <option value=''>--请选择--</option>";
    if(data){
        $.each(data, function(index, val ) {
            console.log( index, val, this );
            htmStr+="<option value='"+val[key]+"' >"+val[value]+"</option>";
        } );
    }
    $(obj).html(htmStr);
}

/*清空表单*/
function clearFrom(formId) {
    var formObj = $("#" + formId);
    if(formId && formObj){
        formObj.clearForm(true);
    }
}
